package tcpClient;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Confirmation {

	private final Queue<String> confirmers = new LinkedList<String>();
	private final Lock lock             = new ReentrantLock();
	private final Condition notFull     = lock.newCondition();
	private final Condition notEmpty    = lock.newCondition();

	
	
	public void in( String name ) throws InterruptedException
	{
		lock.lock();
		try
		{
			while (confirmers.size() == 2)
			{
				System.out.printf("queue voll, kann %s nicht aufnehmen, muss warten.", name);
				notFull.await();
			}

			confirmers.add(name);
//			System.out.printf("%s ist in der queue", name);

			notEmpty.signalAll();
		}
		finally {
			lock.unlock();
		}
	}

	/**
	 * @return the confirmers
	 */
	public Queue<String> getConfirmers() {
		return confirmers;
	}
	
	public void addConfirmer(String name){
		confirmers.add(name);
	}
	


	public String out() throws InterruptedException
	{
		lock.lock();
		try
		{
			while (confirmers.size() == 0)
			{
				System.out.println("Keiner in der queue!");
				notEmpty.await();
			}

			String elem = confirmers.poll();

			notFull.signalAll();

			return elem;
		}
		finally {
			lock.unlock();
		}
	}

}
